package test.n00200;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Problem00210 {
    public static void main(String[] args) {
        println(Arrays.asList(1, 2, 4), Arrays.asList(1, 3, 4));
    }

    public static void println(List<Integer> list1, List<Integer> list2) {
        Solution ss = new Solution();
        System.out.println(list1 + "," + list2 + "," + map(ss.mergeTwoLists(create(list1), create(list2))));
    }

    public static ListNode create(List<Integer> a1) {
        ListNode[] list = new ListNode[a1.size()];
        for (int i = 0; i < a1.size(); i++) {
            list[i] = new ListNode(a1.get(i));
            if (i > 0) {
                list[i - 1].next = list[i];
            }
        }
        return list[0];
    }

    public static List<Integer> map(ListNode head) {
        if (head == null) {
            return Collections.emptyList();
        }
        List<Integer> list = new ArrayList<>();
        while (head != null) {
            list.add(head.val);
            head = head.next;
        }
        return list;
    }

    public static class Solution {

        /**
         * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
         *
         * @param list1
         * @param list2
         * @return
         */
        public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
            ListNode dummy = new ListNode(0);
            ListNode t = dummy;
            while (list1 != null || list2 != null) {
                if (list1 != null && list2 != null) {
                    if (list1.val <= list2.val) {
                        t.next = new ListNode(list1.val);
                        t = t.next;
                        list1 = list1.next;
                    } else {
                        t.next = new ListNode(list2.val);
                        t = t.next;
                        list2 = list2.next;
                    }
                } else if (list1 != null && list2 == null) {
                    t.next = new ListNode(list1.val);
                    t = t.next;
                    list1 = list1.next;
                } else if (list1 == null && list2 != null) {
                    t.next = new ListNode(list2.val);
                    t = t.next;
                    list2 = list2.next;
                } else {
                    return dummy.next;
                }
            }
            return dummy.next;
        }
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
